﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserMessageDA : IUserMessageDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string FROM_USER_ID = "@FROM_USER_ID";
        private string IS_ACTIVE = "@IS_ACTIVE";
        private string IS_READ = "@IS_READ";
        private string MESSAGE_CONTENT = "@MESSAGE_CONTENT";
        private string MESSAGE_TITLE = "@MESSAGE_TITLE";
        private string SQL_CHECK_USER_MESSAGE_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_MESSAGE WHERE ROWID = @ROWID ";
        private string SQL_DELETE_MESSAGE = " DELETE FROM @_@USER_MESSAGE WHERE ROWID = @ROWID ";
        private string SQL_DELETE_USER_MESSAGE = " UPDATE @_@USER_MESSAGE SET IS_ACTIVE = 'Y' WHERE ROWID = @ROWID ";
        private string SQL_INSERT_USER_MESSAGE = " INSERT INTO @_@USER_MESSAGE ( FROM_USER_ID, TO_USER_ID, MESSAGE_TITLE, MESSAGE_CONTENT, SYSTEM_CREATED, IS_READ, IS_ACTIVE, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @FROM_USER_ID, @TO_USER_ID, @MESSAGE_TITLE, @MESSAGE_CONTENT, @SYSTEM_CREATED, @IS_READ, @IS_ACTIVE, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_MARK_USER_MESSAGE = "UPDATE @_@USER_MESSAGE set IS_READ=@IS_READ";
        private string SQL_SELECT_ALL_UNREAD_USER_MESSAGE = "SELECT ROWID,FROM_USER_ID,TO_USER_ID,MESSAGE_TITLE,MESSAGE_CONTENT,UPDATED_DATE FROM @_@USER_MESSAGE WHERE IS_READ = 'N' AND IS_ACTIVE = 'N' ORDER BY UPDATED_DATE DESC";
        private string SQL_SELECT_ALL_USER_MESSAGE = " SELECT  M.ROWID, M.FROM_USER_ID, M.TO_USER_ID, M.MESSAGE_TITLE, M.MESSAGE_CONTENT, M.SYSTEM_CREATED, M.IS_READ, M.IS_ACTIVE, M.CREATED_BY, M.CREATED_DATE, M.UPDATED_BY, M.UPDATED_DATE,U1.USER_NAME AS FROMNAME,U2.USER_NAME AS TONAME  FROM  @_@USER_MESSAGE M LEFT JOIN @_@USER_MST U1 ON U1.USER_ID=M.FROM_USER_ID LEFT JOIN @_@USER_MST U2 ON U2.USER_ID=M.TO_USER_ID ";
        private string SQL_UNREAD_USER_MESSAGE = "SELECT TOP 1 (SELECT COUNT(*) FROM @_@USER_MESSAGE WHERE TO_USER_ID = @TO_USER_ID AND IS_READ = 'N' AND IS_ACTIVE = 'N') AS UNREADQTY,ROWID,FROM_USER_ID,MESSAGE_TITLE,MESSAGE_CONTENT,UPDATED_DATE FROM @_@USER_MESSAGE WHERE TO_USER_ID =@TO_USER_ID AND IS_READ = 'N' AND IS_ACTIVE = 'N' ORDER BY UPDATED_DATE DESC";
        private string SQL_UPDATE_USER_MESSAGE = " UPDATE @_@USER_MESSAGE SET FROM_USER_ID = @FROM_USER_ID, TO_USER_ID = @TO_USER_ID, MESSAGE_TITLE = @MESSAGE_TITLE, MESSAGE_CONTENT = @MESSAGE_CONTENT, SYSTEM_CREATED = @SYSTEM_CREATED, IS_READ = @IS_READ, IS_ACTIVE = @IS_ACTIVE, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE()";
        private string SYSTEM_CREATED = "@SYSTEM_CREATED";
        private string TO_USER_ID = "@TO_USER_ID";
        private string UPDATED_BY = "@UPDATED_BY";

        public bool CheckUserMessageIDUnique(string userMessageID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", userMessageID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_MESSAGE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserMessageIDUnique(DataBase dataBase, DbTransaction tran, string userMessageID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", userMessageID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_MESSAGE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteSendMessage(List<string> userMessageID, string whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < userMessageID.Count; i++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", userMessageID[i]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_MESSAGE.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserMessage(List<string> userMessageID, string whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < userMessageID.Count; i++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", userMessageID[i]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_MESSAGE.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserMessage(DataBase dataBase, DbTransaction tran, List<string> userMessageID, string whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < userMessageID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", userMessageID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_MESSAGE.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUnreadUserMessage(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_UNREAD_USER_MESSAGE.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserMessage(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserMessage(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public DataSet GetInMessageByQueryList(List<string> sqlWhere, UserMessageQueryEntity usermessageQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public UserMessageInfo GetUserMessageByID(string usermessageID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID) + " WHERE M.ROWID = @ROWID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", int.Parse(usermessageID)) };
            UserMessageInfo userMessageInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    userMessageInfo = new UserMessageInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["FROM_USER_ID"].ToString(), reader["TO_USER_ID"].ToString(), reader["MESSAGE_TITLE"].ToString(), reader["MESSAGE_CONTENT"].ToString(), reader["SYSTEM_CREATED"].ToString(), reader["IS_READ"].ToString(), reader["IS_ACTIVE"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime(), reader["FROMNAME"].ToString(), reader["TONAME"].ToString());
                }
            }
            return userMessageInfo;
        }

        public UserMessageInfo GetUserMessageByID(DataBase dataBase, DbTransaction tran, int usermessageID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID) + " WHERE M.ROWID = @ROWID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", usermessageID) };
            UserMessageInfo userMessageInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                userMessageInfo = new UserMessageInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["FROM_USER_ID"].ToString(), reader["TO_USER_ID"].ToString(), reader["MESSAGE_TITLE"].ToString(), reader["MESSAGE_CONTENT"].ToString(), reader["SYSTEM_CREATED"].ToString(), reader["IS_READ"].ToString(), reader["IS_ACTIVE"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime(), reader["FROMNAME"].ToString(), reader["TONAME"].ToString());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return userMessageInfo;
        }

        public DataSet GetUserMessageByQueryList(List<string> sqlWhere, UserMessageQueryEntity usermessageQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!usermessageQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, usermessageQuery.CurrentPage, usermessageQuery.PageSize, usermessageQuery.SortField, usermessageQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserMessageByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserMessageQueryEntity usermessageQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_MESSAGE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, usermessageQuery.CurrentPage, usermessageQuery.PageSize, usermessageQuery.SortField, usermessageQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public UserUnreadMessageInfo GetUserUnreadMessageByID(string userID, string whLoginID)
        {
            string sql = this.SQL_UNREAD_USER_MESSAGE.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@TO_USER_ID", userID) };
            UserUnreadMessageInfo userUnreadMessageInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    userUnreadMessageInfo = new UserUnreadMessageInfo((reader["UNREADQTY"].ToString() != "") ? int.Parse(reader["UNREADQTY"].ToString()) : 0, (reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["FROM_USER_ID"].ToString(), reader["MESSAGE_TITLE"].ToString(), reader["MESSAGE_CONTENT"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return userUnreadMessageInfo;
        }

        public int InsertUserMessage(UserMessageInfo userMessageInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserMessage_Parameters(userMessageInfo);
                if (paras != null)
                {
                    result = db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_MESSAGE.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertUserMessage(DataBase dataBase, DbTransaction tran, UserMessageInfo userMessageInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserMessage_Parameters(userMessageInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_MESSAGE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertUserMessageList(List<UserMessageInfo> userMessageInfoList, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            UserMessageInfo userMessageInfo = null;
            try
            {
                for (int i = 0; i < userMessageInfoList.Count; i++)
                {
                    userMessageInfo = userMessageInfoList[i];
                    SqlParameter[] paras = this.Set_UserMessage_Parameters(userMessageInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_MESSAGE.Replace("@_@", whLoginID), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserMessage_Parameters(UserMessageInfo userMessageInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.FROM_USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.TO_USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.MESSAGE_TITLE, SqlDbType.VarChar, 100), new SqlParameter(this.MESSAGE_CONTENT, SqlDbType.VarChar, 500), new SqlParameter(this.SYSTEM_CREATED, SqlDbType.VarChar, 1), new SqlParameter(this.IS_READ, SqlDbType.VarChar, 1), new SqlParameter(this.IS_ACTIVE, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userMessageInfo.FromUserID;
            paramArray[1].Value = userMessageInfo.ToUserID;
            if (!string.IsNullOrEmpty(userMessageInfo.MessageTitle))
            {
                paramArray[2].Value = userMessageInfo.MessageTitle;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userMessageInfo.MessageContent;
            paramArray[4].Value = userMessageInfo.SystemCreated;
            paramArray[5].Value = userMessageInfo.IsRead;
            paramArray[6].Value = userMessageInfo.IsActive;
            paramArray[7].Value = userMessageInfo.CreatedBy;
            paramArray[8].Value = userMessageInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateMarkUserMessage(string rowIDs, string isRead, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                string sql = this.SQL_MARK_USER_MESSAGE.Replace("@_@", whLoginID) + " WHERE ROWID in (" + rowIDs + ")";
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@IS_READ", isRead) };
                result = db.ExecuteNonQuery(tran, CommandType.Text, sql, paras);
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int UpdateUserMessage(UserMessageInfo userMessageInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserMessage_Parameters(userMessageInfo);
                if ((paras != null) && (userMessageInfo != null))
                {
                    string sql = this.SQL_UPDATE_USER_MESSAGE + " WHERE ROWID =" + userMessageInfo.RowID;
                    result = db.ExecuteNonQuery(tran, CommandType.Text, sql.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int UpdateUserMessage(DataBase dataBase, DbTransaction tran, UserMessageInfo userMessageInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserMessage_Parameters(userMessageInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_MESSAGE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

